package example.cdx.com.aliplayerdemo.utils;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alivc.player.VcPlayerLog;
import com.aliyun.vodplayer.media.AliyunVidSts;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import example.cdx.com.aliplayerdemo.activity.PlayerActivity;
import okhttp3.Call;

/**
 * vid获取的工具类
 */
public class VidStsUtil {

    private static final String TAG = VidStsUtil.class.getSimpleName();

    public static void getVidSts(final String videoId, final OnStsResultListener myStsListener) {
        OkHttpUtils.get()
                .url("https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateSecurityToken?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=" + videoId)
                .build()
                .execute(new StringCallback() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (myStsListener != null) {
                            myStsListener.onFail();
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //解析数据
                        JSONObject jsonObject = JSON.parseObject(response);
                        JSONObject securityTokenInfo = FastJsonUtils.getJsonObject(jsonObject, "SecurityTokenInfo");
                        if (securityTokenInfo == null) {
                            Log.e(TAG, "SecurityTokenInfo == null ");
                            if (myStsListener != null) {
                                myStsListener.onFail();
                            }
                        } else {
                            String accessKeyId = FastJsonUtils.getString(securityTokenInfo, "AccessKeyId");
                            String accessKeySecret = FastJsonUtils.getString(securityTokenInfo, "AccessKeySecret");
                            String securityToken = FastJsonUtils.getString(securityTokenInfo, "SecurityToken");
                            Log.e(TAG, "accessKeyId:" + accessKeyId + " accessKeySecret:" + accessKeySecret + " securityToken:" + securityToken);

                            //将数据暴露给接口
                            if (myStsListener != null) {
                                myStsListener.onSuccess(videoId, accessKeyId, accessKeySecret, securityToken);
                            }
                        }
                    }
                });
    }

    public interface OnStsResultListener {

        void onSuccess(String vid, String akid, String akSecret, String token);

        void onFail();
    }
}
